package finance

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"likeadmin/admin/schemas/req"
	"likeadmin/admin/schemas/resp"
	"likeadmin/constant"
	"likeadmin/core/request"
	"likeadmin/core/response"
	"likeadmin/dao"
	"likeadmin/util"
)

type IUserAccountLogService interface {
	List(c *gin.Context, page request.PageReq, listReq req.UserAccountLogListReq) (res response.PageResp, e error)
}

// NewUserAccountLogService 初始化
func NewUserAccountLogService(db *gorm.DB, dao *dao.Query) IUserAccountLogService {
	return &userAccountLogService{db: db, dao: dao}
}

// userAccountLogService 用户余额变动日志服务实现类
type userAccountLogService struct {
	db  *gorm.DB
	dao *dao.Query
}

// List 用户余额变动日志列表
func (srv userAccountLogService) List(c *gin.Context, page request.PageReq, listReq req.UserAccountLogListReq) (res response.PageResp, e error) {
	// 分页信息
	limit := page.PageSize
	offset := page.PageSize * (page.PageNo - 1)

	m := srv.dao.UserAccountLog
	u := srv.dao.User
	q := m.WithContext(c)

	// 查询
	if listReq.Sn > 0 {
		q = q.Where(m.Sn.Eq(listReq.Sn))
	}
	if listReq.ChangeType > 0 {
		q = q.Where(m.ChangeType.Eq(listReq.ChangeType))
	}

	// 时间范围查询
	if listReq.StartTime != "" && listReq.EndTime != "" {
		startTime, err := util.DateToTimestamp(listReq.StartTime)
		if e = response.CheckErr(err, "DateToTimestamp err"); e != nil {
			return
		}

		endTime, err := util.DateToTimestamp(listReq.EndTime)
		if e = response.CheckErr(err, "DateToTimestamp err"); e != nil {
			return
		}

		q = q.Where(m.CreateTime.Gt(int32(startTime)), m.CreateTime.Lt(int32(endTime)))
	}

	// 总数
	var count int64
	count, err := q.Count()
	if e = response.CheckErr(err, "List Count err"); e != nil {
		return
	}
	// 数据
	objs, err := q.Preload(m.User.Select(u.ID, u.Sn, u.Avatar, u.Nickname, u.Mobile)).Limit(limit).Offset(offset).Order(m.ID.Desc()).Find()
	if e = response.CheckErr(err, "List Find err"); e != nil {
		return
	}

	var resps []resp.UserAccountLogResp
	response.Copy(&resps, objs)

	for i, resp := range resps {
		resps[i].User.Avatar = util.UrlUtil.ToAbsoluteUrl(resp.User.Avatar)
		resps[i].ChangeTypeDesc = constant.GetUserMoneyChangeTypeDesc(resp.ChangeType)
	}
	return response.PageResp{
		PageNo:   page.PageNo,
		PageSize: page.PageSize,
		Count:    count,
		Lists:    resps,
	}, nil
}
